package com.edoomath.mainapp.tencent.handle.impl;

import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.http.annotation.Rao;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.wechat.entity.token.Token;
import com.demo2do.core.wechat.utils.WechatUtils;
import com.edoomath.mainapp.tencent.entity.weappnotice.WeappNoticeSender;
import com.edoomath.mainapp.tencent.handle.WeappNoticeHandler;
import com.edoomath.mainapp.tencent.handle.WeappTokenHandler;
import com.edoomath.mainapp.tencent.rao.WeappNoticeRao;

/**
 * 
 * @author mohanlan
 *
 */
@Component("weappNoticeHandler")
public class WeappNoticeHandlerImpl implements WeappNoticeHandler {
	
	private static final Logger logger = LoggerFactory.getLogger(WeappNoticeHandler.class);
	
	@Autowired
	private WeappTokenHandler weappTokenHandler;
	
	@Rao
	private WeappNoticeRao weappNoticeRao;
	
	/*
	 * (non-Javadoc)
	 * @see com.edoomath.tencent.handle.WeappNoticeHandler#send(com.edoomath.tencent.entity.weappnotice.WeappNoticeSender)
	 */
	public HttpResult send(WeappNoticeSender weappNoticeSender) {
		
		try {
			
			Token token = weappTokenHandler.requestAccessToken();
			
			Map<String, Object> parameters = new HashMap<String, Object>();
			
			parameters.put("touser", weappNoticeSender.getOpenid());
	        parameters.put("template_id", weappNoticeSender.getTemplateId());
	        parameters.put("form_id", weappNoticeSender.getFormId());
	        
	        
	        if(StringUtils.isNotBlank(weappNoticeSender.getPage())) {
	        	parameters.put("page", weappNoticeSender.getPage());
	        }
	        
	        parameters.put("data", weappNoticeSender.getDataParams());
	        parameters.put("emphasis_keyword", weappNoticeSender.getEmphasisKeyword());
	        
	        logger.info("start call send with token [{}] params [{}]", token.getAccessToken(), JsonUtils.toJson(parameters));
	        
	        // execute remote request
	        HttpResult httpResult = weappNoticeRao.send(token.getAccessToken(), parameters);
	        
	        // check result is valid or not
	        if(WechatUtils.isValid(httpResult)) {
	        	return httpResult;
	        }
	        
	        logger.error("#send() - response data [{}] is invalid", httpResult.getResponseText());
	        throw WechatUtils.toBusinessException(httpResult);
			
			
		} catch (Exception e) {
            logger.error("#send() - call weapp notice api occurs a exception [{}]", e);
            throw BusinessException.newInstance("500", "发送消息通知失败");
        }
	}
	
}
